/**
 * 列表页面通用JavaScript功能
 */

// 通用删除确认函数
function confirmDelete(itemName, deleteUrl, itemType = '项目') {
    const message = `确定要删除${itemType} "${itemName}" 吗？\n\n注意：删除后将无法恢复，且可能影响相关数据。`;
    
    if (confirm(message)) {
        try {
            // 创建表单并提交删除请求
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = deleteUrl;
            
            // 添加CSRF token
            const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]');
            if (csrfToken) {
                const csrfInput = document.createElement('input');
                csrfInput.type = 'hidden';
                csrfInput.name = 'csrfmiddlewaretoken';
                csrfInput.value = csrfToken.value;
                form.appendChild(csrfInput);
            }
            
            document.body.appendChild(form);
            form.submit();
        } catch (error) {
            console.error('删除操作失败:', error);
            showAlert('error', '删除操作失败，请重试');
        }
    }
}

// 安全的删除确认函数（用于处理可能不存在的URL）
function safeConfirmDelete(itemName, deleteUrl, itemType = '项目') {
    const message = `确定要删除${itemType} "${itemName}" 吗？\n\n注意：删除后将无法恢复，且可能影响相关数据。`;
    
    if (confirm(message)) {
        try {
            // 检查URL是否有效
            if (!deleteUrl || deleteUrl.includes('undefined') || deleteUrl.includes('null')) {
                showAlert('error', '删除URL无效，请联系管理员');
                return;
            }
            
            // 创建表单并提交删除请求
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = deleteUrl;
            
            // 添加CSRF token
            const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]');
            if (csrfToken) {
                const csrfInput = document.createElement('input');
                csrfInput.type = 'hidden';
                csrfInput.name = 'csrfmiddlewaretoken';
                csrfInput.value = csrfToken.value;
                form.appendChild(csrfInput);
            }
            
            document.body.appendChild(form);
            form.submit();
        } catch (error) {
            console.error('删除操作失败:', error);
            showAlert('error', '删除操作失败，请重试');
        }
    }
}

// 批量操作确认函数
function confirmBatchAction(action, selectedCount) {
    const message = `确定要对选中的 ${selectedCount} 个项目执行"${action}"操作吗？`;
    return confirm(message);
}

// 全选/取消全选功能
function toggleSelectAll(selectAllCheckbox) {
    const checkboxes = document.querySelectorAll('input[name="selected_items"]');
    checkboxes.forEach(checkbox => {
        checkbox.checked = selectAllCheckbox.checked;
    });
    updateBatchActionButtons();
}

// 更新批量操作按钮状态
function updateBatchActionButtons() {
    const selectedCheckboxes = document.querySelectorAll('input[name="selected_items"]:checked');
    const batchActionButtons = document.querySelectorAll('.batch-action-btn');
    const selectedCount = selectedCheckboxes.length;
    
    batchActionButtons.forEach(button => {
        button.disabled = selectedCount === 0;
        const countSpan = button.querySelector('.selected-count');
        if (countSpan) {
            countSpan.textContent = selectedCount;
        }
    });
    
    // 更新全选复选框状态
    const selectAllCheckbox = document.querySelector('#select-all');
    const allCheckboxes = document.querySelectorAll('input[name="selected_items"]');
    if (selectAllCheckbox && allCheckboxes.length > 0) {
        selectAllCheckbox.indeterminate = selectedCount > 0 && selectedCount < allCheckboxes.length;
        selectAllCheckbox.checked = selectedCount === allCheckboxes.length;
    }
}

// 显示提示消息
function showAlert(type, message, duration = 3000) {
    const alertClass = type === 'success' ? 'alert-success' : 
                     type === 'warning' ? 'alert-warning' : 
                     type === 'info' ? 'alert-info' : 'alert-danger';
    
    const alertHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show position-fixed" 
             style="top: 20px; right: 20px; z-index: 9999; min-width: 300px;" role="alert">
            <i class="fas fa-${type === 'success' ? 'check-circle' : 
                              type === 'warning' ? 'exclamation-triangle' : 
                              type === 'info' ? 'info-circle' : 'times-circle'}"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    document.body.insertAdjacentHTML('beforeend', alertHtml);
    
    // 自动消失
    if (duration > 0) {
        setTimeout(() => {
            const alert = document.querySelector('.alert:last-of-type');
            if (alert) {
                const bsAlert = new bootstrap.Alert(alert);
                bsAlert.close();
            }
        }, duration);
    }
}

// 搜索表单自动提交
function setupAutoSubmitSearch() {
    const searchForm = document.querySelector('form[method="get"]');
    if (searchForm) {
        const selectElements = searchForm.querySelectorAll('select');
        selectElements.forEach(select => {
            if (!select.hasAttribute('data-no-auto-submit')) {
                select.addEventListener('change', () => {
                    searchForm.submit();
                });
            }
        });
    }
}

// 表格行点击高亮
function setupRowHighlight() {
    const tableRows = document.querySelectorAll('tbody tr');
    tableRows.forEach(row => {
        row.addEventListener('click', function(e) {
            // 如果点击的是按钮或链接，不执行高亮
            if (e.target.closest('button, a, input')) {
                return;
            }
            
            // 移除其他行的高亮
            tableRows.forEach(r => r.classList.remove('table-active'));
            
            // 添加当前行高亮
            this.classList.add('table-active');
        });
    });
}

// 工具提示初始化
function initTooltips() {
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"], [title]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化批量操作按钮状态
    updateBatchActionButtons();
    
    // 设置复选框事件监听
    const checkboxes = document.querySelectorAll('input[name="selected_items"]');
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', updateBatchActionButtons);
    });
    
    // 设置全选复选框事件监听
    const selectAllCheckbox = document.querySelector('#select-all');
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            toggleSelectAll(this);
        });
    }
    
    // 设置搜索表单自动提交
    setupAutoSubmitSearch();
    
    // 设置表格行高亮
    setupRowHighlight();
    
    // 初始化工具提示
    if (typeof bootstrap !== 'undefined') {
        initTooltips();
    }
});

// 导出功能
function exportData(format, url) {
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = url;
    
    // 添加CSRF token
    const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]');
    if (csrfToken) {
        const csrfInput = document.createElement('input');
        csrfInput.type = 'hidden';
        csrfInput.name = 'csrfmiddlewaretoken';
        csrfInput.value = csrfToken.value;
        form.appendChild(csrfInput);
    }
    
    // 添加格式参数
    const formatInput = document.createElement('input');
    formatInput.type = 'hidden';
    formatInput.name = 'format';
    formatInput.value = format;
    form.appendChild(formatInput);
    
    // 添加当前筛选条件
    const searchParams = new URLSearchParams(window.location.search);
    searchParams.forEach((value, key) => {
        if (key !== 'page') {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = key;
            input.value = value;
            form.appendChild(input);
        }
    });
    
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}

// 刷新页面数据
function refreshData() {
    window.location.reload();
}

// 快捷键支持
document.addEventListener('keydown', function(e) {
    // Ctrl+R 刷新
    if (e.ctrlKey && e.key === 'r') {
        e.preventDefault();
        refreshData();
    }
    
    // Ctrl+A 全选
    if (e.ctrlKey && e.key === 'a') {
        const selectAllCheckbox = document.querySelector('#select-all');
        if (selectAllCheckbox) {
            e.preventDefault();
            selectAllCheckbox.checked = !selectAllCheckbox.checked;
            toggleSelectAll(selectAllCheckbox);
        }
    }
    
    // ESC 取消选择
    if (e.key === 'Escape') {
        const selectAllCheckbox = document.querySelector('#select-all');
        if (selectAllCheckbox) {
            selectAllCheckbox.checked = false;
            toggleSelectAll(selectAllCheckbox);
        }
    }
});